package com.haiyou.common.spring.controller;


import java.util.List;

import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.haiyou.common.constants.ErrCode;
import com.haiyou.common.exception.ServiceException;
import com.haiyou.common.http.AbstractController;
import com.haiyou.common.http.HttpResult;
import com.haiyou.common.system.Properties;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @Description:控制层异常处理 
 * @author xingyuan
 * @date 2022年3月9日 下午2:25:38
 */
@Slf4j
@RestControllerAdvice
public class ControllerAdvice extends AbstractController{

	/**
	 * 接口参数校验异常处理
	 * @param e
	 * @return
	 */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public HttpResult paramVailException(MethodArgumentNotValidException e) {
    	//错误日志打印
    	if(Properties.mvc_advice_error_log()) {
    		//错误日志打印
    		BindingResult result = e.getBindingResult();
    		List<ObjectError> errors = result.getAllErrors();
    		
    		log.error("接口参数校验异常,参数类:{}",result.getTarget().getClass().getSimpleName());
    		for (ObjectError error : errors) {
    			if(error instanceof FieldError) {
    				FieldError fieldError =	(FieldError)error;
    				log.error("{},校验异常",fieldError.getField());
    			}else {
    				log.error(error.getDefaultMessage());
    			}
			}
    	}
    	
    	return failResult(ErrCode.ERROR_PARAMETER, "参数校验异常");
    }
    
    /**
     * 接口缺失参数异常
     * @param e
     * @return
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public HttpResult paramVailException(HttpMessageNotReadableException e) {
    	if(Properties.mvc_advice_error_log()) {
    		log.error(e.getMessage(),e);
    	}
    	return failResult(ErrCode.ERROR_PARAMETER, "参数校验异常");
    }    
    
    /**
     * 所有异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public HttpResult allException(Exception e) {
    	if(Properties.mvc_advice_error_log()) {
    		log.error(e.getMessage(),e);
    	}
    	return failResult(ErrCode.NONE_KNOW_ERROR, "未知异常");
    }
    
    /**
     * 所有异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(ServiceException.class)
    public HttpResult serviceException(ServiceException e) {
    	if(Properties.mvc_advice_error_log()) {
    		log.error(e.getMessage(),e);
    	}
    	return failResult(e.getErrorCode(), e.getMessage());
    }
    
    
    

}
